package simple.cat.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author zheng9feng
 * @Description
 * @Date 2020/12/27 23:35
 */
public class StaticResourceUtil {
	
	/**
	 * 读取静态文件输入流,通过输出流响应给浏览器
	 *
	 * @param inputStream
	 * @param outputStream
	 * @throws Exception
	 */
	public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws Exception {
		// 文件大小-输出内容的总大小
		int totalSize = inputStream.available();
		while (totalSize == 0) {
			totalSize=inputStream.available();
		}
		
		/*
		 * 先输出响应头,再输出html内容
		 */
		outputStream.write(HttpProtocolUtil.getHttpHeader4Success(totalSize).getBytes(StandardCharsets.UTF_8));
		// 加载html文件到输入流,再通过输出流响应给浏览器
		// 缓存数组大小
		byte[] cache = new byte[1024];
		// 实际读到的字节长度：再最后一次从文件读取时，实际读到的字节长度小于等于缓存数组长度
		int actualCacheSize;
		while ((actualCacheSize = inputStream.read(cache)) != -1){
			outputStream.write(cache,0,actualCacheSize);
		}
	}
}
